package com.aididi.socket.controller;

import com.aididi.entity.Message;
import com.aididi.interceptor.SessionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @Auther: zx.xu
 * @Description:
 */
@RestController
public class StompController {

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    @Autowired
    SessionHandler sessionHandler;

    /**
     * 接收客户端发送公告的WebSocket请求
     * @param message
     * @param principal
     * @throws Exception
     */
    //客户端访问服务端的时候config中配置的服务端接收前缀也要加上 例：/webSocket/message
    @MessageMapping("/message")
    public void subscription(Message message, Principal principal) throws Exception {
        messagingTemplate.convertAndSendToUser(message.getTo(), "/queue", new Message(message.getMessage(), message.getDatetime(), message.getFrom(), message.getTo()));
        System.out.println(principal.getName() + "发送了一条消息给：" + message.getTo());
    }

}
